package com.example.woke;

import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.bean.BaseResponse;
import com.bean.MsAreaCode;
import com.bean.MsContactType;
import com.http.HttpMethods;
import com.jakewharton.rxbinding2.view.RxView;
import com.woke.adapter.OnItemClickListener;
import com.woke.data.Category;
import com.woke.fragment.MinShengBussinessCategoriesDialogFragment;
import com.woke.fragment.MsContactTypeDialogFragment;
import com.woke.fragment.MsProvincesAndCitiesDialogFragment;
import com.woke.method.MyApp;
import com.woke.method.NetworkUtils;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.BR;
import com.zhongcai.online.R;
import com.zhongcai.online.databinding.ActivityMinShengMerchantsInBinding;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.xl.xxl.tools.CommonUtil;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * 民生 商户入驻
 */
public class MinShengMerchantsInActivity extends AppCompatActivity {

    private Handler mHandle = new Handler();
    private ActivityMinShengMerchantsInBinding mBinding;
    private MyApp myApp;
    private int pageInde = 0;
    private MinShengBussinessCategoriesDialogFragment mCategoriesDFrag;//经营栏目类型

    private int mPayWay, mChannelWay; //支付方式 和 通道
    private String mTitle;
    private List<Category> mCategorys = new ArrayList<>();//经营栏目类别
    private String mCategoryCode;//选中的经营栏目 对应的编码
    private MsProvincesAndCitiesDialogFragment mProvincesDialogFragment;//省市县
    private MsAreaCode mProvinceAreaCode, mCityAreaCode, mCountyAreaCode;

    private List<MsContactType> mMsContactTypes = new ArrayList<>();//负责人类型
    private MsContactType mContactType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//		setContentView (R.layout.activity_merchants_in);
        Intent intent = getIntent();
        mChannelWay = intent.getIntExtra("way", -1);
        mPayWay = intent.getIntExtra("payway", -1);
        mTitle = intent.getStringExtra("title");

        myApp = MyApp.getInstance();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_min_sheng_merchants_in);
        mBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pageInde > 1) {
                    mBinding.secondViewSwitcher.showPrevious();
                    pageInde--;
                } else if (pageInde > 0) {
                    mBinding.viewSwitcher.showPrevious();
                    pageInde--;
                } else {
                    finish();
                }
            }
        });
        if (TextUtils.isEmpty(mTitle)) {
            mBinding.setVariable(BR.base_list_title, getResources().getString(R.string.title_activity_minshng_merchants_in));
        } else {
            mBinding.setVariable(BR.base_list_title, mTitle);
        }

        initData();


        RxView.clicks(mBinding.merchantsBusinessCategoryTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //商户经营类别
                if (mCategorys.size() > 0) {
                    chooseBussinessCategory(mCategorys);
                } else {
                    getBussinessCategory();
                }
            }
        });
        RxView.clicks(mBinding.merchantProvincesTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //商户省、市、区
                chooseProvinces();
            }
        });

        RxView.clicks(mBinding.merchantContactTypeTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //负责人类型
                if (mMsContactTypes.size() > 0) {
                    chooseContactType(mMsContactTypes);
                } else {
                    getContactType();
                }
            }
        });

        RxView.clicks(mBinding.nextBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //下一步
                String merchantName = mBinding.merchantNameEd.getText().toString();//商户名称
                String merchantShortName = mBinding.merchantShortNameEd.getText().toString();//商户简称
                String merchantAddress = mBinding.merchantAddressEd.getText().toString();//商户地址
                if (TextUtils.isEmpty(merchantName)) {
                    showToast(getResources().getString(R.string.hint_merchants_name));
                    return;
                }
                if (TextUtils.isEmpty(merchantShortName)) {
                    showToast(getResources().getString(R.string.hint_merchants_short_name2));
                    return;
                }

                if (TextUtils.isEmpty(mCategoryCode)) {
                    showToast(getResources().getString(R.string.hint_pu_fa_business_type));
                    return;
                }
                if (mProvinceAreaCode == null || mCityAreaCode == null || mCountyAreaCode == null) {
                    showToast(getResources().getString(R.string.hint_selecte_business_provinces));
                    return;
                }
                if (TextUtils.isEmpty(merchantAddress)) {
                    showToast(getResources().getString(R.string.hint_merchants_address));
                    return;
                }
                if (!NetworkUtils.isConnected(MinShengMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }
                pageInde++;
                mBinding.viewSwitcher.showNext();
            }
        });
        RxView.clicks(mBinding.middleNextBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //下一步
                String service_tel = mBinding.merchantPhoneEd.getText().toString();//客服电话

                String legalPersonName = mBinding.enterpriseLegalPersonEd.getText().toString();//负责人

                String legalPersonPhone = mBinding.merchantContactPhoneEd.getText().toString();//负责人手机

                if (TextUtils.isEmpty(service_tel)) {
                    showToast(getResources().getString(R.string.hint_merchants_phone));
                    return;
                }

                if (TextUtils.isEmpty(legalPersonName)) {
                    showToast(getResources().getString(R.string.hint_enterprise_legal_person_name));
                    return;
                }


                if (!CommonUtil.isPhoneNo(legalPersonPhone)) {
                    showToast(getResources().getString(R.string.hint_phone_not_null));
                    return;
                }

                if (mContactType == null) {
                    showToast(getResources().getString(R.string.hint_merchant_contact_type));
                    return;
                }

                if (!NetworkUtils.isConnected(MinShengMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }
                pageInde++;
                mBinding.secondViewSwitcher.showNext();
            }
        });
        RxView.clicks(mBinding.commitBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //提交商户入驻信息

                String bankAccout = mBinding.merchantsBankAccountEd.getText().toString();    //银行卡号
                String bankCardHolderName = mBinding.merchantsBankAccountNameEd.getText().toString();  //持卡人姓名

                String legalPersonidCard = mBinding.principalIdcardEd.getText().toString();//身份证

                String branchBankName = mBinding.bankNameEd.getText().toString();//支行名称
                if (TextUtils.isEmpty(bankAccout)) {
                    showToast(getResources().getString(R.string.hint_merchants_bank_account));
                    return;
                }

                if (TextUtils.isEmpty(bankCardHolderName)) {
                    showToast(getResources().getString(R.string.hint_merchants_bank_account_name));
                    return;
                }

                if (TextUtils.isEmpty(legalPersonidCard) || legalPersonidCard.length() < 14) {
                    showToast(getResources().getString(R.string.hint_id_card_length));
                    return;
                }

                if (TextUtils.isEmpty(branchBankName)) {
                    showToast(getResources().getString(R.string.hint_branch_bank));
                    return;
                }
                if (!NetworkUtils.isConnected(MinShengMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }

                String merchantName = mBinding.merchantNameEd.getText().toString();//商户名称
                String merchantShortName = mBinding.merchantShortNameEd.getText().toString();//商户简称
                String merchantAddress = mBinding.merchantAddressEd.getText().toString();//商户地址

                String service_tel = mBinding.merchantPhoneEd.getText().toString();//客服电话
                String legalPersonName = mBinding.enterpriseLegalPersonEd.getText().toString();//企业法人
                String legalPersonPhone = mBinding.merchantContactPhoneEd.getText().toString();//法人手机


                Datas_load load = myApp.getDatas_load();
                if (load != null) {
                    String userId = load.getId();
                    if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {

                        Map<String, String> params = new HashMap<>();
                        params.put("userId", userId);
                        params.put("payWay", String.valueOf(mPayWay));
                        params.put("galleryWay", String.valueOf(mChannelWay));
                        params.put("merchantName", merchantName);
                        params.put("shortName", merchantShortName);
                        params.put("category", mCategoryCode);

                        params.put("provinceCode", mProvinceAreaCode.getArea_code());
                        params.put("cityCode", mCityAreaCode.getArea_code());
                        params.put("districtCode", mCountyAreaCode.getArea_code());

                        params.put("merchantAddress", merchantAddress);


                        params.put("servicePhone", service_tel);
                        params.put("contactName", legalPersonName);
                        params.put("contactMobile", legalPersonPhone);

                        params.put("contactType",mContactType.getType());

                        params.put("accNo", bankAccout);
                        params.put("accName", bankCardHolderName);
                        params.put("idCard", legalPersonidCard);
                        params.put("bankName", branchBankName);  //开户银行名称
                        HttpMethods.getInstance().newSettled(mCommitObserver, params);
                    }
                }


            }
        });
    }

    private void initData() {
        Datas_load load = MyApp.getInstance().getDatas_load();
        if (load != null) {
            //联系人电话号码
            mBinding.merchantContactPhoneEd.setText(load.getUser_login());

            //身份证号
            if (!TextUtils.isEmpty(load.getUser_no()) && load.getUser_no().length() >= 15) {
                mBinding.principalIdcardEd.setText(load.getUser_no());
            }
//            if(){}
            //银行卡卡号
            mBinding.merchantsBankAccountEd.setText(load.getCard_no());
            //开户行
//            mBinding.bankNameEd.setText(load.getBank_name());
        }
//        UserInfo userInfo = mRealm.where(UserInfo.class)
//                .equalTo("id", getLocalUserId(this))
//                .findFirst();
//        if (userInfo != null) {
//            //联系人电话号码
//            mBinding.merchantContactPhoneEd.setText(userInfo.getUser_login());
//            //身份证号
//            mBinding.merchantIdcardEd.setText(userInfo.getUser_no());
//            //银行卡卡号
//            mBinding.merchantsBankAccountEd.setText(userInfo.getCard_no());
//            //开户行
//            mBinding.bankNameEd.setText(userInfo.getBank_name());
//        }
    }

    /**
     * 获取经营栏目
     */
    private void getBussinessCategory() {
        if (NetworkUtils.isConnected(this)) {
            HttpMethods.getInstance().getBusinessCategory(mBCategoryObserver, mPayWay);
        } else {
            showToast(getResources().getString(R.string.error_net2));
        }
    }

    private Observer<List<Category>> mBCategoryObserver = new Observer<List<Category>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<Category> categoryList) {


            if (categoryList != null && categoryList.size() > 0) {
                mCategorys.clear();
                mCategorys.addAll(categoryList);
                chooseBussinessCategory(mCategorys);
            }

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    /**
     * 获取负责人类型
     */
    private void getContactType() {
        if (NetworkUtils.isConnected(this)) {
            HttpMethods.getInstance().getContactType(mContactTypeObserver);
        } else {
            showToast(getResources().getString(R.string.error_net2));
        }
    }

    private Observer<List<MsContactType>> mContactTypeObserver = new Observer<List<MsContactType>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<MsContactType> value) {
            if (value != null && value.size() > 0) {
                mMsContactTypes.clear();
                mMsContactTypes.addAll(value);
                chooseContactType(mMsContactTypes);
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (pageInde > 1) {
                mBinding.secondViewSwitcher.showPrevious();
                pageInde--;
                return false;
            } else if (pageInde > 0) {
                mBinding.viewSwitcher.showPrevious();
                pageInde--;
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);

    }

    /**
     * 选择省市
     */
    private void chooseProvinces() {
        if (NetworkUtils.isConnected(this)) {
            if (mProvincesDialogFragment == null) {
                mProvincesDialogFragment = new MsProvincesAndCitiesDialogFragment();
                mProvincesDialogFragment.setOnItemClickListener(mItemClickListener);
            }
            mProvincesDialogFragment.show(getSupportFragmentManager(), "ProvincesAndCities");
        } else {
            showToast(getResources().getString(R.string.error_net2));
        }
    }

    /**
     * 选择经营栏目
     */
    private void chooseBussinessCategory(List<Category> list) {
        if (list != null && list.size() > 0) {

            if (mCategoriesDFrag == null) {
                mCategoriesDFrag = new MinShengBussinessCategoriesDialogFragment();
                mCategoriesDFrag.setOnItemClickListener(mItemClickListener);
            }
            mCategoriesDFrag.setItems(list);
            mCategoriesDFrag.show(getSupportFragmentManager(), "minshengBussinessCategory");
        }

    }

    private MsContactTypeDialogFragment mMsContactTypeDialogFragment;

    private void chooseContactType(List<MsContactType> list) {
        if (list != null && list.size() > 0) {

            if (mMsContactTypeDialogFragment == null) {
                mMsContactTypeDialogFragment = new MsContactTypeDialogFragment();
                mMsContactTypeDialogFragment.setOnItemClickListener(mItemClickListener);
            }
            mMsContactTypeDialogFragment.setItems(list);
            mMsContactTypeDialogFragment.show(getSupportFragmentManager(), "MsContactTypeDialogFragment");
        }

    }


    private OnItemClickListener mItemClickListener = new OnItemClickListener() {

        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof Category) {
                //经营栏目
                if (mCategoriesDFrag != null) {
                    mCategoriesDFrag.dismiss();
                }
                Category category = (Category) object;
                mCategoryCode = category.getCategorycode();
                mBinding.merchantsBusinessCategoryTv.setText(category.getCategoryname());

            } else if (object instanceof MsAreaCode) {
                MsAreaCode areaCode = (MsAreaCode) object;
                if (areaCode.typeArea()) {
                    if (mProvincesDialogFragment != null) {
                        mProvinceAreaCode = mProvincesDialogFragment.getProvinceAreaCode();
                        mCityAreaCode = mProvincesDialogFragment.getCityAreaCode();
                        mCountyAreaCode = mProvincesDialogFragment.getCountyAreaCode();
                        StringBuffer sb = new StringBuffer();
                        sb.append(mProvinceAreaCode.getArea_name()).append(".").append(mCityAreaCode.getArea_name()).append(".").append(mCountyAreaCode.getArea_name());
                        mBinding.merchantProvincesTv.setText(sb.toString());
                    }
                }
            } else if (object instanceof MsContactType) {
                mContactType = (MsContactType) object;
                mBinding.merchantContactTypeTv.setText(mContactType.getName());
                if (mMsContactTypeDialogFragment != null) {
                    mMsContactTypeDialogFragment.dismiss();
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private Observer<BaseResponse> mCommitObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null) {
                if (value.resultSuccess()) {
                    new AlertDialog.Builder(MinShengMerchantsInActivity.this).setTitle("提示").setMessage(value.getInfo()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EventBus.getDefault().post(mChannelWay);
                            finish();
                        }
                    }).create().show();
                } else {
                    showToast(value.getInfo());
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                Log.e("onError",e.getMessage());
            }
        }

        @Override
        public void onComplete() {

        }
    };

}
